package org.example.nettydemo.netty.customize;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liujing
 */
public class CustomizeServer {
    private static final Logger logger = LoggerFactory.getLogger(CustomizeServer.class);

    public static void main(String[] args) {
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);
        EventLoopGroup  workerGroup=new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
//                            pipeline.addLast(new LengthFieldBasedFrameDecoder(1024000, 0, 4, 0, 0));
                            pipeline.addLast(new CustomizeDecoder());
                            pipeline.addLast(new CustomizeServerHandler());
                        }
                    });
            ChannelFuture channelFuture= serverBootstrap.bind(10010).sync();
            logger.info("服务器启动成功，监听端口 10010");
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
